using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Scope;
using IBatisNet.DataMapper.MappedStatements;

namespace Shop.Data.IBatis
{
    /// <summary>
    /// IBatis 的 Dao 基类
    /// </summary>
    public abstract class IBatisDaoBase
    {
        public IBatisDaoBase(string readerName, string writerName)
        {
            this.Reader = IBatisMapperManager.GetMapper(readerName);
            this.Writer = IBatisMapperManager.GetMapper(writerName);
        }

        /// <summary>
        /// 只读库
        /// </summary>
        protected internal ISqlMapper Reader
        {
            get;
            set;
        }

        /// <summary>
        /// 只写库
        /// </summary>
        protected internal ISqlMapper Writer
        {
            get;
            set;
        }

        /// <summary>
        /// 获取运行时SQL
        /// </summary>
        /// <param name="mapper">writer or reader</param>
        /// <param name="statementName">statementName</param>
        /// <param name="paramObject">param</param>
        /// <returns>SQL</returns>
        public string GetRunTimeSql(ISqlMapper mapper, string statementName, object paramObject)
        {
            IMappedStatement statement = mapper.GetMappedStatement(statementName);
            if (!mapper.IsSessionStarted)
            {
                mapper.OpenConnection();
            }
            RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, paramObject, mapper.LocalSession);
            return scope.PreparedStatement.PreparedSql;
        }
    }
}
